package com.yydm.servicemail.controller;

import com.yydm.commonutils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Classname SendMailController
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/7/8 20:26
 * @Created by liu25
 */
@RestController
@RequestMapping("/email")
//@CrossOrigin
public class SendMailController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;

    //    读取配置文件中的username并赋值给username
    @Value("${spring.mail.username}")
    private String username;

    @GetMapping("/sendMail/{email}")
    public R SendMail(@PathVariable String email) {
//       构建一个邮箱对象
        SimpleMailMessage message = new SimpleMailMessage();
//       设置邮件发送者
        message.setFrom(username);
//       设置邮件接收者
        message.setTo(email);
//        设置邮件的主题
        message.setSubject("登录验证码");
//        设置邮件的正文
        String r = "0123456789";
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int ran = random.nextInt(10);
            code.append(r.charAt(ran));
        }
        String text = "您的验证码为:  " + code + "  您的验证码5分钟后失效" + ",请勿泄露给他人。";
//       发送的正文
        message.setText(text);

//        发送邮件
        try {
            javaMailSender.send(message);
//        将验证码保存到redis缓存中,设置有效时间为5分钟
            redisTemplate.opsForValue().set(email, String.valueOf(code), 5, TimeUnit.MINUTES);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error().message("发送失败");
    }

}
